<template>
  <el-card class="message-card" shadow="hover">
    <template #header>
      <div class="card-header">
        <span class="title">消息通知</span>
        <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="unread-badge">
          <el-button type="primary" link @click="goToMessagePage">
            查看全部
          </el-button>
        </el-badge>
      </div>
    </template>
    <div class="message-list">
      <div v-if="latestMessages.length === 0" class="no-message">
        暂无消息通知
      </div>
      <div v-else v-for="message in latestMessages" :key="message.id" class="message-item">
        <div class="message-icon">{{ getTitleIcon(message.title) }}</div>
        <div class="message-content">
          <div class="message-title">{{ message.title }}</div>
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ message.time }}</div>
        </div>
        <div class="message-actions">
          <el-tag 
            v-if="message.status === 'PENDING'" 
            type="warning" 
            effect="light" 
            size="small"
            class="unread-tag"
          >
            未读
          </el-tag>
          <el-tag 
            v-else-if="message.messageType === 'SHARE_NOTE' && message.status === 'ACCEPTED'"
            type="success" 
            effect="light" 
            size="small"
          >
            已接受
          </el-tag>
          <el-tag 
            v-else-if="message.messageType === 'SHARE_NOTE' && message.status === 'REJECTED'"
            type="danger" 
            effect="light" 
            size="small"
          >
            已拒绝
          </el-tag>
          <el-button 
            v-if="message.messageType === 'SHARE_NOTE' && message.status === 'PENDING'"
            type="primary" 
            link 
            @click="viewNoteDetail(message)"
          >
            查看详情
          </el-button>
        </div>
      </div>
    </div>

    <!-- 添加笔记预览对话框 -->
    <el-dialog
      v-model="notePreviewDialog.visible"
      title="笔记详情"
      width="50%"
    >
      <div v-if="notePreviewDialog.note" class="note-preview">
        <h3>{{ notePreviewDialog.note.questionTitle }}</h3>
        <div class="note-content">{{ notePreviewDialog.note.content }}</div>
        <div class="note-meta">
          <span class="note-time">创建时间：{{ formatDate(notePreviewDialog.note.createTime) }}</span>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="notePreviewDialog.visible = false">关闭</el-button>
          <el-button type="success" @click="handleAcceptShare(notePreviewDialog.currentMessage)">接受</el-button>
          <el-button type="danger" @click="handleRejectShare(notePreviewDialog.currentMessage)">拒绝</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const userId = computed(() => userStore.userInfo?.userId || null)
const isLoggedIn = computed(() => userStore.isLoggedIn)

// 消息列表
const messages = ref([])

// 计算属性：按时间排序的消息列表
const sortedMessages = computed(() => {
  return [...messages.value].sort((a, b) => {
    const timeA = new Date(a.time).getTime()
    const timeB = new Date(b.time).getTime()
    return timeB - timeA // 降序排列，最新的消息在前
  })
})

// 计算属性：未读消息数量
const unreadCount = computed(() => {
  return messages.value.filter(msg => !msg.isRead).length
})

// 计算属性：最新的3条消息
const latestMessages = computed(() => {
  return sortedMessages.value.slice(0, 3)
})

// 更新消息状态
const updateMessageStatus = async (messageId, isRead) => {
  try {
    await axios.put(`http://localhost:8080/api/messages/${messageId}/status`, null, {
      params: {
        isRead,
        userId: userId.value
      }
    })
    
    // 更新本地消息状态
    const message = messages.value.find(msg => msg.id === messageId)
    if (message) {
      message.isRead = isRead
    }
  } catch (error) {
    console.error('更新消息状态失败:', error)
    ElMessage.error('更新消息状态失败')
  }
}

// 获取最近日程
const fetchNearestSchedule = async () => {
  if (!isLoggedIn.value || !userId.value) {
    return
  }

  try {
    const response = await axios.get(`http://localhost:8080/schedules/nearest/${userId.value}`)
    
    if (response.data && response.data.schedule) {
      const schedule = response.data.schedule
      const days = response.data.daysToNow
      
      if (schedule && schedule.content) {
        const message = {
          id: Date.now(),
          title: '学习提醒',
          content: `您有一个日程安排：${schedule.content}，距离现在还有${days}天`,
          time: new Date().toISOString(),
          type: 'study',
          isRead: false
        }
        
        // 检查是否已存在相同类型的消息
        const existingIndex = messages.value.findIndex(msg => msg.type === 'study')
        if (existingIndex !== -1) {
          messages.value[existingIndex] = message
        } else {
          messages.value.push(message)
        }
      }
    }
  } catch (error) {
    console.error('获取最近日程失败:', error)
  }
}

// 获取错题数量
const fetchWrongQuestionsCount = async () => {
  if (!isLoggedIn.value || !userId.value) {
    return
  }

  try {
    const response = await axios.get(`http://localhost:8080/wrongquestions/count/byuser`, {
      params: {
        userId: userId.value
      }
    })
    
    const count = response.data
    const message = {
      id: Date.now() + 1,
      title: '错题提醒',
      content: count > 0 ? `您有${count}道错题需要复习` : '您当前没有需要复习的错题',
      time: new Date().toISOString(),
      type: 'wrong',
      isRead: false
    }
    
    // 检查是否已存在相同类型的消息
    const existingIndex = messages.value.findIndex(msg => msg.type === 'wrong')
    if (existingIndex !== -1) {
      messages.value[existingIndex] = message
    } else {
      messages.value.push(message)
    }
  } catch (error) {
    console.error('获取错题数量失败:', error)
  }
}

// 获取消息列表
const fetchMessages = async () => {
  if (!isLoggedIn.value || !userId.value) {
    return
  }

  try {
    const response = await axios.get('http://localhost:8080/api/messages/received', {
      params: { userId: userId.value }
    })
    
    if (response.data.code === 200) {
      // 将后端消息格式转换为前端需要的格式
      const formattedMessages = response.data.data.map(msg => ({
        id: msg.messageId,
        title: msg.title || getMessageTitle(msg.messageType),
        content: msg.content,
        time: msg.createTime,
        type: msg.messageType,
        isRead: msg.status === 'READ',
        messageId: msg.messageId,
        messageType: msg.messageType,
        status: msg.status
      }))
      
      messages.value = formattedMessages
    }
  } catch (error) {
    console.error('获取消息失败:', error)
  }
}

// 获取消息标题
const getMessageTitle = (type) => {
  const titles = {
    'SHARE_NOTE': '笔记分享',
    'SYSTEM': '系统通知',
    'STUDY': '学习提醒',
    'WRONG': '错题提醒',
    'UPDATE': '系统更新',
    'SUGGESTION': '学习建议'
  }
  return titles[type] || '通知'
}

// 监听用户登录状态变化
watch(isLoggedIn, (newValue) => {
  if (newValue) {
    fetchMessages()
    fetchNearestSchedule()
    fetchWrongQuestionsCount()
  } else {
    messages.value = []
  }
})

// 初始化数据
onMounted(async () => {
  if (isLoggedIn.value && userId.value) {
    await fetchMessages()
    await fetchNearestSchedule()
    await fetchWrongQuestionsCount()
  }
})

const getTitleIcon = (title) => {
  const icons = {
    '系统通知': '🔔',
    '学习提醒': '📝',
    '错题提醒': '❌',
    '系统更新': '🔄',
    '学习建议': '💡'
  }
  return icons[title] || '📌'
}

const goToMessagePage = () => {
  router.push('/home/user-center/message')
}

// 添加笔记预览对话框状态
const notePreviewDialog = ref({
  visible: false,
  note: null,
  currentMessage: null
})

// 查看笔记详情
const viewNoteDetail = async (message) => {
  try {
    if (!message.noteId) {
      ElMessage.error('笔记ID不存在')
      return
    }

    const response = await axios.get(`http://localhost:8080/api/notes/shared/${message.noteId}`, {
      params: {
        userId: userId.value
      }
    })

    if (response.data.code === 200) {
      notePreviewDialog.value.note = response.data.data
      notePreviewDialog.value.currentMessage = message
      notePreviewDialog.value.visible = true
    } else {
      ElMessage.error('获取笔记详情失败')
    }
  } catch (error) {
    console.error('获取笔记详情失败:', error)
    ElMessage.error('获取笔记详情失败')
  }
}

// 处理接受分享
const handleAcceptShare = async (message) => {
  try {
    if (!message.messageId) {
      ElMessage.error('消息ID不存在')
      return
    }

    // 更新消息状态为已接受
    await axios.put(`http://localhost:8080/api/messages/${message.messageId}/status`, null, {
      params: {
        status: 'ACCEPTED',
        userId: userId.value
      }
    })

    // 获取分享的笔记内容并复制到用户笔记
    if (message.noteId) {
      const noteResponse = await axios.get(`http://localhost:8080/api/notes/shared/${message.noteId}`, {
        params: {
          userId: userId.value
        }
      })

      if (noteResponse.data.code === 200) {
        const originalNote = noteResponse.data.data
        if (originalNote) {
          // 创建新的笔记
          const createNoteResponse = await axios.post('http://localhost:8080/api/notes/createNote', {
            userId: userId.value,
            questionId: originalNote.questionId,
            content: originalNote.content
          })

          if (createNoteResponse.data.code === 200) {
            ElMessage.success('笔记已成功添加到你的笔记列表')
            notePreviewDialog.value.visible = false
            await fetchMessages() // 刷新消息列表
          } else {
            throw new Error('创建笔记失败')
          }
        }
      }
    }
  } catch (error) {
    console.error('接受分享失败:', error)
    ElMessage.error('接受分享失败')
  }
}

// 处理拒绝分享
const handleRejectShare = async (message) => {
  try {
    if (!message.messageId) {
      ElMessage.error('消息ID不存在')
      return
    }

    await axios.put(`http://localhost:8080/api/messages/${message.messageId}/status`, null, {
      params: {
        status: 'REJECTED',
        userId: userId.value
      }
    })

    ElMessage.success('已拒绝笔记分享')
    notePreviewDialog.value.visible = false
    await fetchMessages() // 刷新消息列表
  } catch (error) {
    console.error('拒绝分享失败:', error)
    ElMessage.error('拒绝分享失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
}
</script>

<style scoped>
.message-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;
  /* 移除与页面布局相关的样式，让父组件控制 */
  /* margin-top: 0 !important; */
  /* max-width: 1200px; */
  /* margin-left: auto; */
  /* margin-right: auto; */
}

/* 恢复 ElCard 默认的 padding */
:deep(.el-card__body) {
  padding: 20px; /* 恢复 ElCard 默认的内边距 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #4a6fa5;
}

.message-list {
  max-height: 300px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid rgba(107, 155, 210, 0.1);
}

.message-item:last-child {
  border-bottom: none;
}

.message-icon {
  font-size: 20px;
  margin-right: 12px;
}

.message-content {
  flex: 1;
}

.message-title {
  font-weight: 500;
  color: #4a6fa5;
  margin-bottom: 4px;
}

.message-text {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.message-time {
  color: #999;
  font-size: 12px;
}

.unread-tag {
  margin-left: 8px;
}

.no-message {
  text-align: center;
  color: #999;
  padding: 20px 0;
}

:deep(.el-card__header) {
  padding: 12px 20px;
  border-bottom: 1px solid rgba(107, 155, 210, 0.1);
}

:deep(.el-badge__content) {
  background: #f56c6c;
}

.message-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.note-preview {
  padding: 20px;
}

.note-preview h3 {
  color: #4a6fa5;
  margin-bottom: 16px;
}

.note-content {
  color: #5a7ba8;
  line-height: 1.6;
  white-space: pre-wrap;
  margin-bottom: 16px;
}

.note-meta {
  color: #8a9bb8;
  font-size: 0.9em;
}

.note-time {
  display: block;
  margin-top: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 